<?php

namespace app\admin\controller;

use think\Controller;
use think\Exception;
use think\Request;
use think\Db;
use app\common\BaseHelper as Helper;
use app\common\Common;


class Adbanner extends Base
{

    public function _initialize()
    {
        parent::_initialize();
        $this->model = 'adbanner';
        $defaultWhere = $this->getDefaultWhere();
        $defaultWhere['is_del'] = ['eq',0];
        $this->defaultWhere = $defaultWhere;
        $adbanner = get_adbanner_list();
        $linktype = get_linktype_list();

        $this->assign('linktype',$linktype);
        $this->assign('adbanner',$adbanner);
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {

        $request = $this->request;
        $param = $request->param();
        // Reset filter
        if ($request->param('reset')) {
            return redirect(fullUrl($request->path()));
        }
        if($request->isAjax()){
            $model = model($this->model);

            // 每页起始条数
            $start = ($param['page'] - 1) * $param['limit'];
            // 每页显示条数
            $length = $param['limit'];
            // 排序条件
            $order = '';

            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                $where = array_merge($this->defaultWhere, $where);
            }
            if($this->defaultOrder){
                $order = $this->defaultOrder;
            }
            $data = $model->where($where)->limit($start, $length)->order('create_date DESC')->select();
            $count = $model->where($where)->count();

            foreach($data as $k => $v)
            {
                $v['type'] = show_adbanner_list($v['type']);
                $v['key'] = $k + 1;
                $v['start_time'] = substr($v['start_time'],0,10);
                $v['end_time'] = substr($v['end_time'],0,10);
            }

            $result = [
                'code' => '0',
                'msg' => '请求成功',
                'data' => $data,
                'count' => $count,
            ];

            return json($result);
        }else{
            return self::show($this->indexView, [
                'pageSize' => ['url' => fullUrl($request->path())],
                'searchFields' => $this->searchFields,
                'param' => $request->param()
            ]);
        }


    }

    /**
     * Add
     */
    public function add(Request $request)
    {
        return parent::add($request);
    }

    /*
     * savePost
     * */
    public function savePost(Request $request, $redirect = '')
    {
        $param = $request->param();
        $model = model($this->model);
        $error = $this->checkparam($param);
        if($error['code'] != 0){
            return $this->error($error['msg']);
        }

        if (!empty($param['link_detail_product'])){
            $param['link_detail_product'] = implode(',',$param['link_detail_product']);
        }

        if (!empty($param['status_link_type'])){
            //链接位置
            $param['status_link'] = 1;
            unset($param['link_detail_product']);
            unset($param['link_product']);
        }else if (!empty($param['status_detail_product'])){
            //专题商品
            $param['status_link'] = 2;
            unset($param['link_type']);
            unset($param['link_product']);
        }else{
            //单个商品
            $param['status_link'] = 3;
            unset($param['link_type']);
            unset($param['link_detail_product']);
        }

        if ($request->isAjax()){
            if (empty($param['id'])){
                //新增
                if ($param['type'] == 4){
                    //弹屏广告只能有一条
                    $verify = $model->where('type',4)->find();
                    if ($verify){
                        return $this->error('弹屏广告只能有一条');
                    }
                }

                $param['id'] = Helper::getUUID();
                Db::startTrans();
                $param['create_date'] = date('Y-m-d H:i:s',time());
                $result = $model->create($param,true);

                if (!$result){
                    Db::rollback();
                    return $this->error($model->getError());
                }

                $logInfo = $this->admin->name . '添加了一条' . lang($this->model) . '数据。';

                if($result !== false) {
                    // Query执行后的操作
                    $model->_after_update($param);
                    Db::commit();
                    // 写入日志
                    Common::adminLog($request, $logInfo);
                    return $this->success('添加成功！', 'admin/adbanner/index');
                } else {
                    Db::rollback();
                    return $this->error($model->getError());
                }
            }else{
                //修改
                Db::startTrans();
                $time = $model->where('id',$param['id'])->field('create_date')->find();
                $result = $model->where('id',$param['id'])->delete();
                if (!$result){
                    Db::rollback();
                    return $this->error($model->getError());
                }
                $param['update_date'] = date('Y-m-d',time());
                $param['create_date'] = $time['create_date'];

                $result = $model->create($param,true);
                if (!$result){
                    Db::rollback();
                    return $this->error($model->getError());
                }

                $verify = $model->where('type',4)->count();
                if ($verify >= 2){
                    Db::rollback();
                    return $this->error('弹屏广告只能有一条');
                }
                $logInfo = $this->admin->name . '修改了一条' . lang($this->model) . '数据。';

                if($result !== false) {
                    // Query执行后的操作
                    $model->_after_update($param);

                    // 写入日志
                    Common::adminLog($request, $logInfo);
                    Db::commit();
                    return $this->success('修改成功！', 'admin/adbanner/index');
                } else {
                    Db::rollback();
                    return $this->error($model->getError());
                }
            }
        }else{
            return $this->error('请求方式错误!');
        }
    }

    public function edit(Request $request)
    {
        $param = $request->param();
        $model = model($this->model);
        $productMdl = model('product');
        if (empty($param['id'])){
            return $this->error('未接收到id');
        }
        $id = $param['id'];
        $info = $model->find($id);
        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }
        if (!empty($info['link_detail_product'])){
            $product = explode(',',$info['link_detail_product']);
            foreach ($product as $v){
                $product_detail[] = $productMdl->where('id',$v)->field('id as pro_id,name as pro_name')->find();
            }
            $info['link_detail_product'] = $product_detail;
        }
        if (!empty($info['link_product'])){
            $info['link_product'] = $productMdl->where('id',$info['link_product'])->field('id as pro_id,name as pro_name')->find();
        }
        $info['start_time'] = substr($info['start_time'],0,10);
        $info['end_time'] = substr($info['end_time'],0,10);

        return $this->show($this->editView, [
            'info' => $info
        ]);
    }

    //验证规则
    private function checkparam($param)
    {
        if (empty($param['title_url'])){
            $error['code'] = '400020';
            $error['msg'] = '轮播图为空!';
            return $error;
        }
        if (empty($param['name'])){
            $error['code'] = '400021';
            $error['msg'] = '广告名称为空!';
            return $error;
        }
        if (empty($param['type'])){
            $error['code'] = '400022';
            $error['msg'] = '广告形式为空!';
            return $error;
        }
        if (!empty($param['status_detail_product']) && !empty($param['status_one_product']) && !empty($param['status_link_type'])){
            $error['code'] = '400024';
            $error['msg'] = '专题商品/单个商品/链接位置只能选择一个!';
            return $error;
        }
        if (empty($param['status_detail_product']) && empty($param['status_one_product']) && empty($param['status_link_type'])){
            $error['code'] = '400025';
            $error['msg'] = '专题商品/单个商品/链接位置必须选择一个!';
            return $error;
        }
        if (!empty($param['status_detail_product'])){
            if (empty($param['link_detail_product'])){
                $error['code'] = '400026';
                $error['msg'] = '专题商品内容不能为空!';
                return $error;
            }
        }

        if (!empty($param['status_detail_product'])){
            if (count($param['link_detail_product']) != count(array_unique($param['link_detail_product']))) {
                $error['code'] = '400026';
                $error['msg'] = '专题商品重复!';
                return $error;
            }
        }
        if ($param['start_time'] == $param['end_time']){
            $error['code'] = '400027';
            $error['msg'] = '开始时间不能等于结束时间!';
            return $error;
        }

        if (strtotime($param['start_time']) > strtotime($param['end_time'])){
            $error['code'] = '400027';
            $error['msg'] = '开始时间不能小于结束时间!';
            return $error;
        }

        $error['code'] = 0;
        $error['msg'] = '';
        return $error;
    }

    //选择优惠商品
    public function get_product_all()
    {
        return $this->fetch();
    }
    //选择单间优惠商品
    public function get_product_one()
    {
        return $this->fetch();
    }

    //渲染商品
    public function get_product_list(Request $request)
    {
        $param = $request->param();
        $productMdl = model('product');
        $where = [
            'a.status' => ['neq', 0],
            'a.type' => ['neq', 3],
            'a.is_gift' => 2
        ];
        if(isset($param['name']) && $param['name']){
            $where['a.name'] = ['like', '%'.$param['name'].'%'];
        }
        $fields = 'a.id,a.name,a.bar_code,a.unit,a.store_count,a.price,p.name as typeName';
        $data = $productMdl->alias('a')
            ->where($where)
            ->join('product_category p','a.category_id = p.id')
            ->field($fields)
            ->select();
        foreach ($data as $item)
        {
            $item['unit'] = show_product_unit($item['unit']);
            // 库存
            $item['qty'] = $productMdl->getStock($item['id']);
        }
        $result = [
            'code' => '0',
            'msg' => '请求成功',
            'data' => $data,
        ];
        return json($result);
    }

    public function handle(Request $request){
        $param = $request->param();
        if(empty($param['id']) || empty($param['status'])){
            return $this->error('缺少参数');
        }
        if($param['status'] ==1 || $param['status'] == 2){
            \app\admin\model\Adbanner::where('id',$param['id'])->update(['status'=>$param['status']]);
            return $this->success('操作成功');
        }else{
            return $this->error('参数不合法');
        }
    }

    public function delete(){
        $param = Request::instance()->param();
        if(!empty($param['id'])){
            try{
                \app\admin\model\Adbanner::where('id',$param['id'])->update(['is_del'=>1]);
                return $this->success('删除成功');
            }catch (Exception $ex){
                return $this->error('删除失败');
            }
        }else{
            return $this->error('参数不合法');
        }
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if(isset($param['name']) && $param['name']){
            $where['name'] = ['like', '%'.$param['name'].'%'];
        }
        return $where;
    }

    private function show($template, $data = []) {

        return $this->view->fetch($template, $data);
    }
}
